import { http } from "@/utils/http";

export interface MenuItem {
  id?: number;
  parentId?: number;
  name: string;
  path?: string;
  component?: string;
  icon?: string;
  /** 菜单类型：0 目录 | 1 菜单 | 2 按钮 */
  type: number;
  perms?: string;
  sort: number;
  /** 是否外链/内嵌（根据后端：true/false）*/
  isFrame?: boolean;
  /** 后端可能存在的冗余字段 */
  status?: number;
  visible?: number;
  delFlag?: string;
  parentName?: string;
  level?: number;
  createTime?: string;
  updateTime?: string;
  children?: MenuItem[];
}

export interface MenuResult {
  code: number;
  data: MenuItem[];
  message: string;
}

export interface MenuTreeResult {
  code: number;
  data: MenuItem[];
  message: string;
}

export interface MenuDetailResult {
  code: number;
  data: MenuItem;
  message: string;
}

export interface MenuCreateResult {
  code: number;
  data: number; // 返回新创建的菜单ID
  message: string;
}

export interface MenuUpdateResult {
  code: number;
  data: boolean;
  message: string;
}

export interface MenuDeleteResult {
  code: number;
  data: boolean;
  message: string;
}

/** 获取菜单树 */
export const getMenuTree = () => {
  return http.request<MenuTreeResult>("get", "menu/all");
};

/** 获取菜单列表 */
export const getMenuList = (params?: any) => {
  return http.request<MenuResult>("get", "menu/list", { params });
};

/** 获取菜单详情 */
export const getMenuDetail = (id: number) => {
  return http.request<MenuDetailResult>("get", `admin/menu/${id}`);
};

/** 创建菜单 */
export const createMenu = (data: Omit<MenuItem, "id">) => {
  return http.request<MenuCreateResult>("post", "menu/add", { data });
};

/** 更新菜单 */
export const updateMenu = (id: number, data: Partial<MenuItem>) => {
  return http.request<MenuUpdateResult>("post", `/menu/update`, { data });
};

/** 删除菜单 */
export const deleteMenu = (id: number) => {
  return http.request<MenuDeleteResult>("get", `menu/delete/${id}`);
};

/** 批量删除菜单 */
export const batchDeleteMenu = (ids: number[]) => {
  return http.request<MenuDeleteResult>("delete", "admin/menu/batch", {
    data: { ids }
  });
};

/** 更新菜单状态 */
export const updateMenuStatus = (id: number, status: number) => {
  return http.request<MenuUpdateResult>("put", `admin/menu/${id}/status`, {
    data: { status }
  });
};

/** 更新菜单排序 */
export const updateMenuSort = (id: number, sort: number) => {
  return http.request<MenuUpdateResult>("put", `admin/menu/${id}/sort`, {
    data: { sort }
  });
};
